package com.htwy.core.handler;

import com.jfinal.handler.Handler;
import com.jfinal.kit.LogKit;
import com.jfinal.kit.PathKit;
import com.jfinal.kit.StrKit;
import com.jfinal.render.RenderException;
import com.jfinal.render.RenderManager;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class StaticResourceHandler extends Handler{

    protected static final String DEFAULT_CONTENT_TYPE = "application/octet-stream";

    private String encodeFileName(HttpServletRequest request, String fileName) {
        String userAgent = request.getHeader("User-Agent");
        try {
            String encodedFileName = URLEncoder.encode(fileName, "UTF8");
            // 如果没有UA，则默认使用IE的方式进行编码
            if (userAgent == null) {
                return "filename=\"" + encodedFileName + "\"";
            }

            userAgent = userAgent.toLowerCase();
            // IE浏览器，只能采用URLEncoder编码
            if (userAgent.indexOf("msie") != -1) {
                return "filename=\"" + encodedFileName + "\"";
            }

            // Opera浏览器只能采用filename*
            if (userAgent.indexOf("opera") != -1) {
                return "filename*=UTF-8''" + encodedFileName;
            }

            // Safari浏览器，只能采用ISO编码的中文输出,Chrome浏览器，只能采用MimeUtility编码或ISO编码的中文输出
            if (userAgent.indexOf("safari") != -1 || userAgent.indexOf("applewebkit") != -1 || userAgent.indexOf("chrome") != -1) {
                return "filename=\"" + new String(fileName.getBytes("UTF-8"), "ISO8859-1") + "\"";
            }

            // FireFox浏览器，可以使用MimeUtility或filename*或ISO编码的中文输出
            if (userAgent.indexOf("mozilla") != -1) {
                return "filename*=UTF-8''" + encodedFileName;
            }

            return "filename=\"" + encodedFileName + "\"";
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public void handle(String target, HttpServletRequest request, HttpServletResponse response, boolean[] isHandled) {
        if(target.indexOf("/static/") > -1){
            File file = new File(PathKit.getWebRootPath(),target);
            if(file.exists()){
                response.setHeader("Content-disposition", "attachment; " + encodeFileName(request, file.getName()));
                response.setHeader("Accept-Ranges", "bytes");
                String contentType = request.getServletContext().getMimeType(file.getName());
                response.setContentType(contentType != null ? contentType : DEFAULT_CONTENT_TYPE);

                if (StrKit.isBlank(request.getHeader("Range"))) {
                    try {
                        normalRender(response, new FileInputStream(file));
                    } catch (FileNotFoundException e) {
                        RenderManager.me().getRenderFactory().getErrorRender(404).render();
                    }
                } else {
                    try {
                        rangeRender(request, response, new FileInputStream(file));
                    } catch (FileNotFoundException e) {
                        RenderManager.me().getRenderFactory().getErrorRender(404).render();
                    }
                }
            }else{
                InputStream is = getClass().getResourceAsStream("/com/htwy"+target);
                if(is == null){
                    RenderManager.me().getRenderFactory().getErrorRender(404).render();
                }else {
                    String filename = getFileName(target);
                    response.setHeader("Content-disposition", "attachment; " + encodeFileName(request, filename));
                    response.setHeader("Accept-Ranges", "bytes");
                    String contentType = request.getServletContext().getMimeType(file.getName());
                    response.setContentType(contentType != null ? contentType : DEFAULT_CONTENT_TYPE);

                    if (StrKit.isBlank(request.getHeader("Range"))) {
                        normalRender(response, is);
                    } else {
                        rangeRender(request, response, is);
                    }
                }

            }
            if (isHandled.length > 0) {
                isHandled[0] = true;
            }
        }else{
            next.handle(target,request,response,isHandled);
        }
    }

    private String getFileName(String target) {
        return  target.substring(target.lastIndexOf("/")+1);
    }

    protected void normalRender(HttpServletResponse response, InputStream is) {
        try {
            response.setHeader("Content-Length", String.valueOf(is.available()));
        } catch (IOException e) {
            e.printStackTrace();
        }
        InputStream inputStream = null;
        OutputStream outputStream = null;
        try {
            inputStream = new BufferedInputStream(is);
            outputStream = response.getOutputStream();
            byte[] buffer = new byte[1024];
            for (int len = -1; (len = inputStream.read(buffer)) != -1;) {
                outputStream.write(buffer, 0, len);
            }
            outputStream.flush();
            outputStream.close();
        } catch (IOException e) {
            String n = e.getClass().getSimpleName();
            if (n.equals("ClientAbortException") || n.equals("EofException")) {
            } else {
                throw new RenderException(e);
            }
        } catch (Exception e) {
            throw new RenderException(e);
        } finally {
            if (inputStream != null)
                try {inputStream.close();} catch (IOException e) {
                    LogKit.error(e.getMessage(), e);}
        }
    }

    protected void rangeRender(HttpServletRequest request, HttpServletResponse response, InputStream is) {
        Long[] range = {null, null};
        long fileLength = 0;
        try {
            fileLength = is.available();
        } catch (IOException e) {
            e.printStackTrace();
        }
        processRange(request, fileLength, range);

        String contentLength = String.valueOf(range[1].longValue() - range[0].longValue() + 1);
        response.setHeader("Content-Length", contentLength);
        response.setStatus(HttpServletResponse.SC_PARTIAL_CONTENT);	// status = 206

        // Content-Range: bytes 0-499/10000
        StringBuilder contentRange = null;

        contentRange = new StringBuilder("bytes ").append(String.valueOf(range[0])).append("-").append(String.valueOf(range[1])).append("/").append(String.valueOf(fileLength));
        response.setHeader("Content-Range", contentRange.toString());

        InputStream inputStream = null;
        OutputStream outputStream = null;
        try {
            long start = range[0];
            long end = range[1];
            inputStream = new BufferedInputStream(is);
            if (inputStream.skip(start) != start)
                throw new RuntimeException("File skip error");
            outputStream = response.getOutputStream();
            byte[] buffer = new byte[1024];
            long position = start;
            for (int len; position <= end && (len = inputStream.read(buffer)) != -1;) {
                if (position + len <= end) {
                    outputStream.write(buffer, 0, len);
                    position += len;
                }
                else {
                    for (int i=0; i<len && position <= end; i++) {
                        outputStream.write(buffer[i]);
                        position++;
                    }
                }
            }
            outputStream.flush();
            outputStream.close();
        }
        catch (IOException e) {
            String n = e.getClass().getSimpleName();
            if (n.equals("ClientAbortException") || n.equals("EofException")) {
            } else {
                throw new RenderException(e);
            }
        }
        catch (Exception e) {
            throw new RenderException(e);
        }
        finally {
            if (inputStream != null)
                try {inputStream.close();} catch (IOException e) {LogKit.error(e.getMessage(), e);}
        }
    }

    /**
     * Examples of byte-ranges-specifier values (assuming an entity-body of length 10000):
     * The first 500 bytes (byte offsets 0-499, inclusive): bytes=0-499
     * The second 500 bytes (byte offsets 500-999, inclusive): bytes=500-999
     * The final 500 bytes (byte offsets 9500-9999, inclusive): bytes=-500
     * 															Or bytes=9500-
     */
    protected void processRange(HttpServletRequest request, long fileLength, Long[] range) {
        String rangeStr = request.getHeader("Range");
        int index = rangeStr.indexOf(',');
        if (index != -1)
            rangeStr = rangeStr.substring(0, index);
        rangeStr = rangeStr.replace("bytes=", "");

        String[] arr = rangeStr.split("-", 2);
        if (arr.length < 2)
            throw new RuntimeException("Range error");

        for (int i=0; i<range.length; i++) {
            if (StrKit.notBlank(arr[i])) {
                range[i] = Long.parseLong(arr[i].trim());
                if (range[i] >= fileLength)
                    range[i] = fileLength - 1;
            }
        }

        // Range format like: 9500-
        if (range[0] != null && range[1] == null) {
            range[1] = fileLength - 1;
        }
        // Range format like: -500
        else if (range[0] == null && range[1] != null) {
            range[0] = fileLength - range[1];
            range[1] = fileLength - 1;
        }

        // check final range
        if (range[0] == null || range[1] == null || range[0].longValue() > range[1].longValue())
            throw new RuntimeException("Range error");
    }

}
